package com.gitee.form_token.service;

import com.gitee.form_token.common.*;
import com.gitee.form_token.dto.LoginDto;
import com.gitee.form_token.entity.MyUserDetails;
import com.gitee.form_token.token.JwtUtil;
import com.gitee.form_token.token.TokenDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class MyLoginService {

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private MyUserDetailsPasswordService myUserDetailsPasswordService;

    public Result checkLogin(LoginDto login) {
        String username = login.getUsername();
        String password = login.getPassword();

        if (username == null || password == null) {
            return Result.fail(Const.loginNullMsg);
        }

        // 封装到待认证的 authRequest 对象中
        UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);

        try {
            // 发起认证
            Authentication authentication = authenticationManager.authenticate(authRequest);

            // 登录成功
            if (authentication.isAuthenticated()) {
                // 设置到上下文
                SecurityContextHolder.getContext().setAuthentication(authentication);

                // 转换数据
                MyUserDetails myUser = (MyUserDetails) authentication.getPrincipal();
                // System.out.println("LoginService -> myUser==" + myUser);

                // 升级密码 -- 可选项
                // myUserDetailsPasswordService.updatePassword(myUser, password);

                // 生成令牌
                // 生成令牌
                TokenDto subject = new TokenDto();
                subject.setUser(myUser.getUsername());
                subject.setUid(myUser.getAccount().getId());
                subject.setRid(myUser.getAccount().getRoleId());
                String token = JwtUtil.createToken(subject, Const.WebIssuerKey);

                // 写入缓存
                String redisKey = "user:" + subject;
                redisUtil.set(redisKey, myUser, ValueUtil.redisExpire);

                System.out.println("token===" + token);
                return Result.success(token);
            }
        } catch (AuthenticationException ex) {
            return Result.fail(ex.getMessage());
        }

        return Result.fail("认证失败");
    }
}
